////////////////////////////////////////////////////////////////////////////////
//Copyright (c) 2010 Michal Szczepanski - (http://vane.pl)
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
package pl.vane.net.services
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;

	/**
	 *  @private
	 */
	[Event(name="event.ready", type="flash.events.Event")]
	
	/**
	 * URLLoaderBase Class is responsible for loading content.
	 * 
	 * It's URLStream wrapper different from URLLoader
	 * 
	 * @see flash.net.URLLoader
	 * @see flash.net.URLRequest
	 * 
	 * @langversion ActionScript 3.0
	 * @playerversion Flash 9.0
	 * @tiptext
	 */ 
	public class URLLoaderBase extends EventDispatcher implements IURLLoaderBase
	{
		
		/**
		 * @private
		 */
		private var _responder:IURLResponder;
		
		/**
		 * @private
		 */
		private var _url:String;
		
		/**
		 * @private
		 */
		private var _busy:Boolean = false;
		
		/**
		 * @private
		 */ 
		private var stream:URLStream;
		
		/**
		 * @private
		 */ 
		public var dataFormat:String;
		
		/**
		 * @private
		 */ 
		public var data:*;
		
		/**
		 * @private
		 */ 
		public var bytesLoaded:uint;// = 0
		
		/**
		 * @private
		 */ 
		public var bytesTotal:uint;// = 0
		
		/**
		 * @private
		 */ 
		private var _status:int;
		
		/**
		 * @private
		 */
		private var _progress:Function;
		
		/**
		 * Constructor.
		 * 
		 * @langversion ActionScript 3.0
		 * @playerversion Flash 9.0
		 * @tiptext
		 */	
		public function URLLoaderBase(progress:Function = null, weak:Boolean = false){
			_progress = progress;
			stream = new URLStream;
			stream.addEventListener(Event.OPEN, redirectEvent);
			stream.addEventListener(IOErrorEvent.IO_ERROR, onComplete);
			stream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			stream.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusEvent);
			if(_progress)
				stream.addEventListener(ProgressEvent.PROGRESS, _progress);
			stream.addEventListener(Event.COMPLETE, onComplete);
		}
		
		/**
		 * Loads Request from the service and put data to the responder.
		 * 
		 * @param request URLRequest data
		 * @param responder IURLRespodner that holds the response from the service
		 * 
		 * @langversion ActionScript 3.0
		 * @playerversion Flash 9.0
		 * @tiptext
		 */
		public function loadRequest(request:URLRequest, responder:IURLResponder):void {
			_responder = responder;
			_url = request.url;
			this.stream.load(request);
			_busy = true;
		}
		
		/**
		 * Returns the <code>true</code> if the URLLoaderBase is performing 
		 * some action or <code>false</code> if it's ready to use
		 * 
		 * @langversion ActionScript 3.0
		 * @playerversion Flash 9.0
		 * @tiptext
		 */ 
		public function get busy():Boolean {
			return _busy;
		}
		
		/**
		 * Returns the <code>String</code> url of the current request.
		 * 
		 * @langversion ActionScript 3.0
		 * @playerversion Flash 9.0
		 * @tiptext
		 */ 
		public function get url():String {
			return _url;
		}
		
		/**
		 * Removes all requests from the URLLoader service.
		 * 
		 * @langversion ActionScript 3.0
		 * @playerversion Flash 9.0
		 * @tiptext
		 */ 
		public function removeListeners():void {
			stream.removeEventListener(Event.OPEN, redirectEvent);
			stream.removeEventListener(IOErrorEvent.IO_ERROR, onComplete);
			stream.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			stream.removeEventListener(HTTPStatusEvent.HTTP_STATUS, statusEvent);
			if(_progress)
				stream.removeEventListener(ProgressEvent.PROGRESS, _progress);
			stream.removeEventListener(Event.COMPLETE, onComplete);
		}
		
		/**
		 * Destroys the URLLoaderBase.
		 * 
		 * @langversion ActionScript 3.0
		 * @playerversion Flash 9.0
		 * @tiptext
		 */ 
		public function dispose():void {
			this.stream.close();
			data = null;
			_responder = null
			_url = null;
			_busy = false;
		}
		
		/**
		 * @private
		 */
		protected function securityErrorHandler(event:SecurityErrorEvent):void {
			_responder.fault([_url, event.text, event.type]);
			dispose();
			
		}
		
		/**
		 * @private
		 */ 
		private function statusEvent(event:HTTPStatusEvent):void {
			dispatchEvent(event);
			_status = event.status;
		}
		
		/**
		 * @private
		 */ 
		private function redirectEvent(event:Event):void{
			dispatchEvent(event);
		}
		
		/**
		 * @private
		 */ 
		private function onComplete(event:Event):void{
			var bytes:ByteArray = new ByteArray();
			this.stream.readBytes(bytes);
			switch (this.dataFormat){
				case "binary":
					this.data = bytes;
					break;
				case "variables":
					this.data = new URLVariables(bytes.toString());
					break;
				case "text":
				default:
					this.data = bytes.toString();
					break;
			};
			switch(_status) {
				case 0:   _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "WTF"]);break;
				case 200: dispatchEvent(event); break;
				case 201: _responder.result("Created"); break; 
				case 202: _responder.result("Accepted"); break; 
				case 304: _responder.result("Not Modified"); break; 
				case 400: _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "Bad Request"]);break;
				case 404: _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "Not Found"]);break;
				case 405: _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "Resource Not Allowed"]);break;
				case 409: _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "Conflict"]);break;
				case 412: _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "Precondition Failed"]);break;
				case 500: _responder.fault([_url, (IOErrorEvent)(event).text, event.type, "Internal Server Error"]);break;
			}
			dispose();
			dispatchEvent(new Event('event.ready'));
		}
	}
}